import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import './styles/index.scss' // 全局样式
import { createPinia } from 'pinia'
import { permission } from './directives/permission'
import { useUserStore } from './store/user'

const app = createApp(App)

// 注册Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

const pinia = createPinia()
app.use(pinia)

// 在路由导航前进行用户信息的加载
router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore();
  const token = localStorage.getItem('token');

  if (token && !userStore.userInfo.id) { // 如果有token但用户信息未加载
    await userStore.getUserInfoAction();
    await userStore.fetchMenuList();
  }
  next();
});

app.use(router)
// 全局配置Element Plus为中文
app.use(ElementPlus, { locale: zhCn })

app.directive('permission', permission)

app.mount('#app')
